<template>
  <div class="creator-review">
    <n-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ t('menu.creatorReview') }}</span>
          <n-button size="small" quaternary @click="resetColumnWidths">
            <template #icon>
              <n-icon><Icons name="refresh-outline" /></n-icon>
            </template>
            重置列宽
          </n-button>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-input
              v-model:value="searchForm.username"
              :placeholder="t('user.username')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.creatorStatus"
              :placeholder="t('user.creatorStatus')"
              clearable
              :options="creatorStatusOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1200"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" title="创作者详情" style="width: 600px">
      <div class="creator-detail" v-if="currentUser">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-item">
            <label>用户名:</label>
            <span>{{ currentUser.username }}</span>
          </div>
          <div class="detail-item">
            <label>邮箱:</label>
            <span>{{ currentUser.email }}</span>
          </div>
          <div class="detail-item">
            <label>注册时间:</label>
            <span>{{ currentUser.createTime }}</span>
          </div>
          <div class="detail-item">
            <label>最后登录:</label>
            <span>{{ currentUser.lastLoginTime }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>创作数据</h4>
          <div class="detail-item">
            <label>发表文章:</label>
            <span>{{ currentUser.articlesCount }} 篇</span>
          </div>
          <div class="detail-item">
            <label>粉丝数量:</label>
            <span>{{ currentUser.followersCount }} 人</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>申请状态</h4>
          <div class="detail-item">
            <label>当前状态:</label>
            <n-tag :type="getCreatorStatusType(currentUser.creatorStatus)" size="small">
              {{ getCreatorStatusText(currentUser.creatorStatus) }}
            </n-tag>
          </div>
        </div>

        <div class="review-actions" v-if="currentUser.creatorStatus === 'pending'">
          <n-space>
            <n-button type="success" @click="handleApprove(currentUser)">
              通过申请
            </n-button>
            <n-button type="error" @click="handleReject(currentUser)">
              拒绝申请
            </n-button>
          </n-space>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDataTable,
  NTag,
  NModal,
  NSpace,
  NAvatar,
  useMessage,
  useDialog
} from 'naive-ui'
import { EyeOutline, CheckmarkCircleOutline, CloseCircleOutline } from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import { userApi } from '@/api'

const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const showModal = ref(false)
const currentUser = ref<any>(null)

const searchForm = reactive({
  username: '',
  creatorStatus: null
})

const tableData = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => t('common.total', { count: itemCount })
})

const creatorStatusOptions = computed(() => [
  { label: t('user.creatorStatus.pending'), value: 'pending' },
  { label: t('user.creatorStatus.approved'), value: 'approved' },
  { label: t('user.creatorStatus.rejected'), value: 'rejected' }
])

const getCreatorStatusType = (status: string) => {
  switch (status) {
    case 'approved':
      return 'success'
    case 'pending':
      return 'warning'
    case 'rejected':
      return 'error'
    default:
      return 'default'
  }
}

const getCreatorStatusText = (status: string) => {
  return t(`user.creatorStatus.${status}`)
}

const getCreatorStatusTag = (status: string) => {
  return h(NTag, { 
    type: getCreatorStatusType(status),
    size: 'small' 
  }, () => getCreatorStatusText(status))
}

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 50,
    maxWidth: 100
  },
  {
    title: t('user.username'),
    key: 'username',
    width: 150,
    minWidth: 120,
    maxWidth: 200,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center;' }, [
        h(NAvatar, { 
          size: 'small', 
          src: row.avatar,
          fallbackSrc: '/images/default-avatar.svg',
          style: 'margin-right: 8px;'
        }),
        h('span', row.username)
      ])
    }
  },
  {
    title: t('user.email'),
    key: 'email',
    width: 180,
    minWidth: 150,
    maxWidth: 250,
    ellipsis: { tooltip: true }
  },
  {
    title: '申请状态',
    key: 'creatorStatus',
    width: 120,
    minWidth: 100,
    maxWidth: 160,
    render: (row: any) => getCreatorStatusTag(row.creatorStatus)
  },
  {
    title: t('user.articlesCount'),
    key: 'articlesCount',
    width: 100,
    minWidth: 80,
    maxWidth: 150
  },
  {
    title: t('user.followersCount'),
    key: 'followersCount',
    width: 100,
    minWidth: 80,
    maxWidth: 150
  },
  {
    title: t('common.createTime'),
    key: 'createTime',
    width: 160,
    minWidth: 120,
    maxWidth: 200
  },
  {
    title: t('common.operation'),
    key: 'actions',
    width: 240,
    minWidth: 200,
    maxWidth: 300,
    resizable: false,
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          onClick: () => handleView(row)
        }, { default: () => t('common.view'), icon: () => h(NIcon, () => h(EyeOutline)) })
      ]

      if (row.creatorStatus === 'pending') {
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleApprove(row),
            style: { marginLeft: '8px' }
          }, { default: () => '通过', icon: () => h(NIcon, () => h(CheckmarkCircleOutline)) }),
          
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleReject(row),
            style: { marginLeft: '8px' }
          }, { default: () => '拒绝', icon: () => h(NIcon, () => h(CloseCircleOutline)) })
        )
      }
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'creator-review',
  defaultWidths: {
    'id': 60,
    'username': 150,
    'email': 180,
    'creatorStatus': 120,
    'articlesCount': 100,
    'followersCount': 100,
    'createTime': 160,
    'actions': 240
  }
})

const columns = computed(() => resizableColumns.value)

const loadData = async () => {
  try {
    loading.value = true
    const response = await userApi.getList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      role: 'creator',
      ...searchForm
    })
    if (response.success) {
      // 只显示创作者角色的用户
      tableData.value = response.data.list.filter((item: any) => item.role === 'creator')
      pagination.itemCount = tableData.value.length
    }
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.username = ''
  searchForm.creatorStatus = null
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleView = (row: any) => {
  currentUser.value = row
  showModal.value = true
}

const handleApprove = (row: any) => {
  dialog.info({
    title: '确认操作',
    content: `确认通过用户"${row.username}"的创作者申请吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await userApi.approveCreator(row.id)
        message.success('审核通过')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleReject = (row: any) => {
  dialog.warning({
    title: '确认操作',
    content: `确认拒绝用户"${row.username}"的创作者申请吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await userApi.rejectCreator(row.id)
        message.success('已拒绝申请')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.creator-detail {
  padding: 16px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  margin-right: 12px;
  width: 80px;
  flex-shrink: 0;
}

.review-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
  text-align: center;
}
</style>